#include "Http.hpp"
#include "HttpServer.hpp"

#define HTTP_STATIC_RESOURCE_PATH "www"

std::string SerializeRequest(const HttpRequest& req)
{
    std::stringstream ss;
    ss << req._method << " " << req._path << " " << req._version << "\r\n";// 响应行
    for(auto& pair : req._params)// 查询字符串
    {
        ss << pair.first << ": " << pair.second << "\r\n";
    }
    for(auto& pair : req._headers)// 响应头部
    {
        ss << pair.first << ": " << pair.second << "\r\n";
    }
    ss << "\r\n";// 空行
    ss << req._body;// 响应正文
    return ss.str();
}

void HelloHandle(const HttpRequest& req, HttpResponse* resp)
{
    resp->SetContent(SerializeRequest(req), "text/plain");
    // sleep(6);// 测试超时释放
}

void PutFile(const HttpRequest& req, HttpResponse* resp)
{
    INF_LOG("SERVER IS DOWNLOADING FILES FROM CLIENT");
    std::string resourcePath = HTTP_STATIC_RESOURCE_PATH + req._path;
    Utils::WriteFile(resourcePath, req._body);
    INF_LOG("SERVER DOWNLOADS FILES FROM CLIENT SUCCESS");
}

int main()
{
    HttpServer server(9000, 10);
    server.SetThreadCount(3);
    server.SetRootPath(HTTP_STATIC_RESOURCE_PATH);
    server.AddGetRoute("/hello", HelloHandle);
    server.AddPostRoute("/hello", HelloHandle);
    server.AddHeadRoute("/hello", HelloHandle);
    server.AddDeleteRoute("/hello", HelloHandle);
    server.AddPutRoute("/uploadFile.txt", PutFile);
    

    INF_LOG("SERVER LISTING PORT:9000 INITIALIZES SUCCESS");
    server.Listen();

    return 0;
}